package com.heartech.prediciton_wx.utils.token;

import com.heartech.prediciton_wx.constant.WxCode;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


@Slf4j
public class AccessTokenUtil {
    public static String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WxCode.appid + "&secret=" + WxCode.secret;

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                String jsonResponse = response.toString();
                log.info("JSON Response :: " + jsonResponse);
                return parseAccessToken(jsonResponse);
            } else {
                log.error("GET request not worked");
            }
        } catch (IOException e) {
            log.error("Error getting access_token", e);
        }

        return null;
    }

    private static String parseAccessToken(String jsonResponse) {
        try {
            JSONObject json = new JSONObject(jsonResponse);
            return json.getString("access_token");
        } catch (JSONException e) {
            log.error("Error parsing access_token", e);
        }
        return null;
    }
}
